<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onBeforeMount, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  province: '',
  city: '',
  district: ''
})
// ----
const forToPay = proxy.$route.query.toPay ? JSON.parse(proxy.$route.query.toPay) : {}
const forExtend = proxy.$route.query.exTend ? JSON.parse(proxy.$route.query.exTend) : {}
// ----
const forToName = proxy.$forToPage || 'UcenTer'
// ----
const code = reactive({
  info: '获取验证码',
  count: 60,
  isClick: false
})
const isMobile = /^(1[3456789]\d{9})$/
const form = reactive({
  telphone: '',
  smscode: ''
})

/* ---- */
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  // --获取信息--
  const newItems = forSys.filter((item) => { return String(item.name) === 'market_service' })
  if (Number(newItems.length) === 1) {
    proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      const RJData = resJson[0] || {}
      // ----
      if (RJData.province) user.province = RJData.province
      if (RJData.city) user.city = RJData.city
      if (RJData.district) user.district = RJData.district
    })
  }
}
// ----
const forTime = () => {
  code.isClick = !code.isClick
  const timer = () => {
    if (code.count > 0) {
      const forCount = code.count < 10 ? '0' + code.count : code.count
      code.info = forCount + '秒后重发'
      code.count--
      setTimeout(timer, 1000)
    } else {
      code.info = '获取验证码'
      code.count = 60
      code.isClick = !code.isClick
    }
  }
  timer()
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
const getAuditFun = (type) => {
  switch (Number(type)) {
    case 1: {
      if (code.isClick) return false
      if (!isMobile.test(form.telphone)) {
        proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
        return false
      }
      // ----
      proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
      proxy.$http.post('wechat/get-mobile-code', {
        telphone: form.telphone,
        is_reg_check: 1,
        SmsType: 3,
        // ----
        config_id: userInfo.config_id,
        openid: userInfo.openid
      }).then((res) => {
        proxy.$Myfun.disLoading(layerLoading.value, 'close')
        if (res.success) {
          forTime()
        } else { proxy.$Myfun.forToast(layer.value, 'open', res.message) }
      }).catch((err) => {
        proxy.$Myfun.disLoading(layerLoading.value, 'close')
        proxy.$Myfun.forToast(layer.value, 'open', err)
      })
      break
    }
  }
}
// ----
const subform = async () => {
  if (!isMobile.test(form.telphone)) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写合法的手机号！')
    return false
  }
  if (Number(form.smscode.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写获取的验证码！')
    return false
  }
  // ----
  const forType = 'post'
  const forUrl = 'wechat/login'
  const forData = {
    telphone: form.telphone,
    smscode: form.smscode,
    sn: proxy.$Store.get('SN') || undefined,
    source: proxy.$Source || undefined,
    is_saler: 0,
    // --新用户增加默认地区--
    province: user.province || undefined,
    city: user.city || undefined,
    district: user.district || undefined,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = {}
  await proxy.$http[forType](forUrl, forData).then((res) => {
    if (res.success && res.datainfo) {
      resData = res.datainfo
    } else { proxy.$Myfun.forToast(layer.value, 'open', res.message) }
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  // ----
  if (resData && Number(Object.keys(resData).length) > 0) {
    // --设置缓存--
    const wzModule = proxy.$Store.get('wz_module')
    const WXConfig = proxy.$Store.get('WXConfig')
    const forClick = proxy.$Store.get('forClick')
    const forSearch = proxy.$Store.get('forSearch')
    proxy.$Store.clear(() => {
      proxy.$Store.set('wz_module', wzModule)
      proxy.$Store.set('WXConfig', WXConfig)
      proxy.$Store.set('forClick', forClick)
      proxy.$Store.set('logUser', resData)
      proxy.$Store.set('SN', resData.sn)
      if (forSearch) proxy.$Store.set('forSearch', forSearch)
    })
    // --针对团队成员 & 合作企业登录报名--
    if (proxy.$route.query.capitalType) {
      await proxy.$http.get('teams/index', {
        params: {
          'TeamsSearch[to_dealer_id]': resData.id,
          'TeamsSearch[type]': proxy.$route.query.capitalType
        }
      }).then((resSign) => {
        if (Number(resSign.items.length) > 0) {
          proxy.$router.back()
        } else {
          proxy.$Myfun.openPage(proxy, 'replace', forToName)
        }
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
      return false
    }
    // --针对商圈登录报名--
    if (proxy.$route.query.meet_id) {
      await proxy.$http.get('meeting-joincm/index', {
        params: {
          'MeetingJoincmSearch[meeting_id]': proxy.$route.query.meet_id,
          'MeetingJoincmSearch[dealer_id]': resData.id
        }
      }).then((resSign) => {
        if (Number(resSign.items.length) > 0) {
          proxy.$router.back()
          return false
        }
      }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
    }
    // --针对总管理员登录--
    if (String(proxy.$Phone) === String(resData.telphone)) {
      if (proxy.$route.query.toName) {
        proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.query.toName, forExtend.opts)
      } else if (Number(Object.keys(forToPay).length) > 0 || proxy.$route.query.toBack) {
        proxy.$router.back()
      } else {
        proxy.$Myfun.openPage(proxy, 'replace', forToName, proxy.$route.query)
      }
      return false
    }
    // --针对登录并充值--
    if (Number(Object.keys(forToPay).length) > 0) {
      let workLine = []
      proxy.$Myfun.getJsonData(resData.topupze, (resJson) => { workLine = resJson })
      let amountDate = 0
      workLine.some((oneItem) => {
        if (String(oneItem.id) === String(forToPay.payType)) {
          oneItem.info.some((twoItem) => {
            if (String(twoItem.id) === String(forToPay.payId)) amountDate = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
          })
        }
      })
      const curDate = Date.parse(new Date())
      if (Number(amountDate) >= Number(curDate)) {
        if (proxy.$route.query.toName) {
          proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.query.toName, forExtend.opts)
        } else {
          proxy.$router.back()
        }
      } else {
        proxy.$Myfun.openPage(proxy, 'replace', 'PaySys', proxy.$route.query)
      }
      return false
    }
    // --针对常规指向登录--
    if (proxy.$route.query.toName) {
      if (forExtend.name) {
        let workLine = []
        proxy.$Myfun.getJsonData(resData.topupze, (resJson) => { workLine = resJson })
        let amountDate = 0
        workLine.some((oneItem) => {
          if (String(oneItem.id) === String(forExtend.payType)) {
            oneItem.info.some((twoItem) => {
              if (String(twoItem.id) === String(forExtend.payId)) amountDate = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
            })
          }
        })
        const curDate = Date.parse(new Date())
        if (Number(amountDate) < Number(curDate) && Number(forExtend.opts.dealer_id) !== Number(resData.id)) {
          proxy.$Myfun.openPage(proxy, 'replace', forExtend.name)
          return false
        }
      }
      proxy.$Myfun.openPage(proxy, 'replace', proxy.$route.query.toName, forExtend.opts)
      return false
    }
    // --针对登录后返回来源页--
    if (proxy.$route.query.toBack) {
      proxy.$router.back()
      return false
    }
    // ----
    proxy.$Myfun.openPage(proxy, 'replace', forToName, proxy.$route.query)
  }
}

/* ---- */
onBeforeMount(() => {
  if (Number(Object.keys(logUser).length) > 0) proxy.$router.back()
})
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>手机号码</i>
            <p class="xw-flex-W1"><input class="text" placeholder="" v-model.trim="form.telphone"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.telphone"></em></transition>
          </div>
        </li>
        <li class="xw-flex xw-flex-align">
          <div class="form-txt xw-radius-3 xw-flex-W1 xw-flex xw-flex-align">
            <i>短信验证</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.smscode"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.smscode"></em></transition>
          </div>
          <span class="xw-radius-3" :class="[code.isClick ? 'form-btn-time' : 'form-btn xw-WBlue']" @click="getAuditFun(1)">{{code.info}}</span>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
    </div>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>
